from .Emulator import Emulator, Device
from external.containers.emu import docker_device, emu_docker, emu_downloads_menu

import subprocess
import logging
import time
import sys


class DockerEmulator(Emulator):

    def __init__(self, path_config, configuration, ):
        Device.__init__(self, path_config, configuration, 'DockerEmulator')
        print(configuration)
        self.image_info = configuration.get("image_info")
        self.emu_info = configuration.get("emu_info")

    def connect(self):
        stdout = b""
        stderr = b""
        while not b"connected" in stdout and not b"connected" in stderr:
            pid = subprocess.Popen([self.adb_path, 'connect', "localhost"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            pid.wait()
            stdout, stderr = pid.communicate()

            print(stderr)
            time.sleep(0.5)

    def start(self):
        logging.debug("Starting docker")
        if(self.emu_info.strip() != "" and self.image_info.strip() != ""):
            img = emu_downloads_menu.select_image(True,self.image_info) or sys.exit(1)
            emulator = emu_downloads_menu.select_emulator(self.emu_info) or sys.exit(1)
        else:
            img = emu_downloads_menu.select_image(True) or sys.exit(1)
            emulator = emu_downloads_menu.select_emulator() or sys.exit(1)



        img_zip = img.download()
        emu_zip = emulator.download("linux")
        self.device_docker = emu_docker.DockerDevice(emu_zip, img_zip, "android")
        self.device_docker.create_docker_file()
        img = self.device_docker.create_container()
        if img:
            self.container = self.device_docker.launch(img)

            # Steps :
            # - Launch device
            # - Connect to it (localhost:5555)
            # - Wait for booting up
            self.connect()
            self.device_id = "localhost:5555"

            pid = subprocess.Popen([self.adb_path, '-s', self.device_id, "root"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            pid.wait()
            self.check_is_up()

    def kill_emulators(self):
        logging.debug("DockerEmulator:kill_emulators")
        pid = subprocess.Popen(["docker", "kill", self.container.name], stdout=subprocess.PIPE)
        pid.wait()
        pid = subprocess.Popen(["docker", "rm", self.container.name], stdout=subprocess.PIPE)
        pid.wait()


